package com.frogs.ucenter.v1.service.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.util.PageList;
import com.frogs.system.util.AttentionStateEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.FamilyBaseInfoDao;
import com.frogs.ucenter.dao.UserAttentionInfoDao;
import com.frogs.ucenter.entity.FamilyBaseInfo;
import com.frogs.ucenter.entity.ext.FamilyBaseInfoExt;
import com.frogs.ucenter.v1.request.FamilyBaseInfoAddRequest;
import com.frogs.ucenter.v1.request.FamilyBaseInfoDetailRequest;
import com.frogs.ucenter.v1.request.FamilyBaseInfoUpdateRequest;
import com.frogs.ucenter.v1.request.FamilyDataStatRequest;
import com.frogs.ucenter.v1.request.FamilyListRequest;
import com.frogs.ucenter.v1.request.FamilyRankingListRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.ListResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.response.UpdateResponse;
import com.frogs.ucenter.v1.service.FamilyBaseInfoService;
import com.frogs.ucenter.v1.util.ApiConstants;

/**
 *
 * @author wushubin
 */
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"familyBaseInfoService")
public class FamilyBaseInfoServiceImpl implements FamilyBaseInfoService{
	
	private static final Logger log = LoggerFactory.getLogger(FamilyBaseInfoServiceImpl.class);
	
	@Resource
	private FamilyBaseInfoDao familyBaseInfoDao;
	
	@Resource
	private UserAttentionInfoDao userAttentionInfoDao;
	
	/**
	 * 新增家庭圈（创建用户时，家庭圈同时也建立，暂时不会单独调用到家庭圈的建立）
	 * 
	 * @param request
	 * @return
	 */
	@Override
	public Response addFamilyBaseInfo(Request request) {
		AddResponse<FamilyBaseInfo> response = new AddResponse<FamilyBaseInfo>();
		FamilyBaseInfoAddRequest familyBaseInfoAddRequest = (FamilyBaseInfoAddRequest)request;
		try {
			FamilyBaseInfo object = new FamilyBaseInfo();
			object.setUserId(familyBaseInfoAddRequest.getUserId());
			object.setName(familyBaseInfoAddRequest.getName());
			familyBaseInfoDao.insert(object);
			
			response.setInfo(object);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						 request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	/**
	 * 修改家庭圈
	 */
	@Override
	public Response updateFamilyBaseInfo(Request request) {
		UpdateResponse<FamilyBaseInfo> response = new UpdateResponse<FamilyBaseInfo>();
		FamilyBaseInfoUpdateRequest familyBaseInfoUpdateRequest = (FamilyBaseInfoUpdateRequest)request;
		try {
			FamilyBaseInfo familyBaseInfo = familyBaseInfoDao.selectById(familyBaseInfoUpdateRequest.getId());
			if(familyBaseInfo.getUserId().intValue() == familyBaseInfoUpdateRequest.getUserId()){
				familyBaseInfo.setName(familyBaseInfoUpdateRequest.getName());
				familyBaseInfoDao.update(familyBaseInfo);
				response.setInfo(familyBaseInfo);
			}else{
				throw new ServiceOperationException("请求处理失败：你没有权限修改家庭圈" );
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						 request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 获取家庭信息(包括了排名)
	 */
	@Override
	public Response getFamilyBaseInfo(Request request) {
		ShowResponse<FamilyBaseInfoExt> response = new ShowResponse<FamilyBaseInfoExt>();
		FamilyBaseInfoDetailRequest familyBaseInfoDetailRequest = (FamilyBaseInfoDetailRequest)request;
		try {
			FamilyBaseInfoExt ext = familyBaseInfoDao.selectExtByUserId(familyBaseInfoDetailRequest.getUserId());
			response.setInfo(ext);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						 request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	/**
	 * 统计关注的总人数和总积分，计算家庭圈繁荣度
	 */
	@Override
	public Response statistics(Request request) {
		DefaultResponse response = new DefaultResponse();
		FamilyDataStatRequest familyDataStatRequest = (FamilyDataStatRequest)request;
		try {
			FamilyBaseInfo familyBaseInfo  = familyBaseInfoDao.selectById(familyDataStatRequest.getFamilyId());
			
			if(familyBaseInfo.getUserId().intValue() == familyDataStatRequest.getUserId()){
				//只查已经同意关注的总人数，计算总人数和总积分
				Map<String,Object> params = new HashMap<String,Object>();
				params.put("eqUserId", familyDataStatRequest.getUserId() );
				params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
				Map<String, Object> result = userAttentionInfoDao.statisticById(params);
				if(result.get("memberNumber") != null){
					int memberNumber = Integer.parseInt(result.get("memberNumber").toString()) + 1;//记得加上自己
					int totalPoints = Integer.parseInt(result.get("totalPoints").toString());
					familyBaseInfo.setMemberNumber(memberNumber);
					//换算为家庭圈的繁荣度
					familyBaseInfo.setProsperity(Integer.valueOf((int)(memberNumber * 1000 * 0.3 + totalPoints * 0.7)));
					familyBaseInfo.setProsperityUpdateTime(new Date());
					familyBaseInfoDao.update(familyBaseInfo);
				}
			}else{
				throw new ServiceOperationException("请求处理失败：你没有权限修改家庭圈" );
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						 request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	/**
	 * 查询排行版
	 */
	@Override
	public Response getRankingList(Request request) {
		PageListResponse<FamilyBaseInfoExt> response = new PageListResponse<FamilyBaseInfoExt>();
		try {
			FamilyRankingListRequest familyRankingListRequest = (FamilyRankingListRequest)request;
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("orderByClause", " prosperity desc, id asc " );
			PageList<FamilyBaseInfoExt> pageList = familyBaseInfoDao.selectExtByMap(params, familyRankingListRequest.getPageNo(), 
										familyRankingListRequest.getPageSize(), true);
			response.setList(pageList);
			response.setPageTurn(pageList.getPageTurn());
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	/**
	 * 我加入的家庭圈列表（默认最大为501个）
	 */
	@Override
	public Response getFamilyList(Request request) {
		ListResponse<FamilyBaseInfo> response = new ListResponse<FamilyBaseInfo>();
		try {
			FamilyListRequest familyListRequest = (FamilyListRequest)request;
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("eqUserId",familyListRequest.getUserId() );
			List<FamilyBaseInfo> list = familyBaseInfoDao.selectByMap(params, 1, 1, false);
			list.addAll(familyBaseInfoDao.selectMyAllFamily(params));
			response.setList(list);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
		
}
